package com.dayuanit.dy16.atm.boatm.test;

import java.util.concurrent.*;

public class ThreadPoolUtils {
    public static void main(String[] args) {
        //线程池的工具类

        //不推荐使用工具类创建线程池 因为队列的容量 无法控制，容易产生内存溢出
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        //初始化时，木有线程，当任务来的时候，再临时创建线程，若线程空闲，则60s之后会销毁。
        //缺点，在任务比较多的 情况下，会创建大量的线程，暂用过多的系统资源。任意产生内存溢出。
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

        //单列的线程池  能够保证任务的按照顺序执行
        ExecutorService singleThread = Executors.newSingleThreadExecutor();

        //定时器的线程池
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);

//        scheduledThreadPool.scheduleWithFixedDelay(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println(Thread.currentThread().getName() + " >>>>>>>>>>>");
//            }
//        }, 0, 3, TimeUnit.SECONDS);
//
//        scheduledThreadPool.scheduleWithFixedDelay(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println(Thread.currentThread().getName() + " ##############");
//            }
//        }, 0, 5, TimeUnit.SECONDS);



        //推荐 ***** 使用底层的ThreadPoolExecutor创建线程池，虽然参数多了点，但是整体是可控的，比如队列大小，线程名称以及拒绝策略
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 2,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(100));


        Future<String> future = threadPoolExecutor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println(Thread.currentThread().getName() + " tomcat init...");
                Thread.sleep(10*1000);
                System.out.println(Thread.currentThread().getName() + " tomcat start...");
                return "tomcat";
            }
        });

        Future<String> future2 = threadPoolExecutor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println(Thread.currentThread().getName() + " spring init...");
                Thread.sleep(10*1000);
                System.out.println(Thread.currentThread().getName() + " spring start...");
                return "spring";
            }
        });

        System.out.println(Thread.currentThread().getName() + " 准备得到结果...");

        try {
            //get方法会阻塞，直到任务完成，才能返回结果，程序才能继续往下执行
            String result = future.get();
            String result2 = future2.get();
            System.out.println("result=" + result);
            System.out.println("result2=" + result2);
        } catch (Exception e) {
            e.printStackTrace();
        }


        System.out.println("main over.");
    }
}
